/**
 * @description: 初始化插件配置
 * @return {*}
 */
function init(callback) {
  const currentTabType = tabTypes.find((t) => location.href.includes(t.url));
  chrome.runtime.sendMessage(
        {
          type: "options",
        },
        function (response) {
          console.log("response - ", response);
        }
      );
  if (currentTabType && currentTabType.source) {
    globalData.source = currentTabType.source;
    injectJs("js/inject.js", async () => {
      const accountInfo = await getUserInfo(currentTabType.source);
      if(!accountInfo) return false
      const applyFlag = await getApplyInfo(currentTabType.source)
      
      // if(!applyFlag) return false
      const auth = await authentication(currentTabType.source, accountInfo);
      if(!auth) return false
      await getConfiguration(currentTabType.source);

      callback && callback();
      return true

    });
  } else {
    return false;
  }
}

/**
 * @description: 获取登陆账号信息
 * @param {*} source
 * @return {*}
 */
async function getUserInfo(source) {
  let accountInfo = "";
  switch (source) {
    case 7:
      accountInfo = await getUserDDInfo();
      break;
    case 10:
      accountInfo = await getUserKSInfo();
      break;
  }
  return accountInfo;
}

/**
 * @description: 获取快手账号信息  待定
 * @return {*}
 */
function getUserKSInfo() {
  return new Promise(async (resolve) => {
    const userid = localStorage.getItem("seller-pc-userid")
      if (userid) {
      const initialUserInfo = await getKSUserInfo(userid);
      if (initialUserInfo) {
        userInfo.shopName = initialUserInfo.shopName;
        const {
          quota: { used_quota, unused_quota },
          canApply,
          applicationNum,
        } = await ksApiGetQuota();
        userInfo.used_quota = used_quota;
        userInfo.unused_quota = unused_quota;
        userInfo.canApply = canApply;
        pluginInfo.applicationNum = applicationNum;
        resolve(userInfo.shopName);
      } else {
        resolve(false);
        // window.history.go(0);
      }
    }
  });
}

/**
 * @description: 获取抖店账号信息
 * @return {*}
 */
function getUserDDInfo() {
  return new Promise(async (resolve) => {
    let initialUserInfo = JSON.parse(sessionStorage.getItem("initialUserInfo"));
    if (initialUserInfo && initialUserInfo.code == 0) {
      userInfo.shopId = initialUserInfo.data.id;
      userInfo.token = initialUserInfo.data.token;
      const { used_quota, unused_quota } = await ddApiGetQuota(userInfo.token);
      userInfo.used_quota = used_quota;
      userInfo.unused_quota = unused_quota;
      resolve(userInfo.shopId);
    } else {
      resolve(false);
      // window.history.go(0);
    }
  });
}

/**
 * @description: 获取账号提额权限
 * @param {*} source
 * @return {*}
 */
async function getApplyInfo(source){
  let applyInfo = false;
  switch (source) {
    case 7:
      applyInfo = await getApplyInfoDD();
      break;
    case 10:
      applyInfo = await getApplyInfoKS();
      break;
  }
  return applyInfo;
}

/**
 * @description: 获取账号提额权限 抖店
 * @return {*}
 */
function getApplyInfoDD(){
  return new Promise((resolve, reject) => {
    ddGetReceiveInfoViewQuotaApplyInfo().then(res => {
      // ApplydeQuotaTimes  今日剩余提额次数
    // Status   1  无风险，可提额     2  解密额度已冻结，不可申请     4  请用完当日解密额度后再申请     6  您的提额申请正在审批中
      const {Status, ApplydeQuotaTimes} = res
      userInfo.canApply = Status === 1 && Number(ApplydeQuotaTimes) > 0
      resolve(userInfo.canApply)
    })
  })
}

/**
 * @description: 获取账号提额权限 快手
 * @return {*}
 */
 function getApplyInfoKS(){
  return new Promise((resolve) => {
    const {unused_quota, canApply} = userInfo
    const {applicationNum} = pluginInfo
    const flag = canApply && applicationNum > unused_quota
    resolve(flag)
  })
}



/**
 * @description: 获取插件配置信息
 * @param {*} source 店铺类型
 * @return {*}
 */
function getConfiguration(source) {
  return new Promise(async (resolve, reject) => {
    try {
      switch (source) {
        case 7:
          await getDDConfiguration();
          break;
        case 10:
          await getKSConfiguration();
          break;
      }
      const reason = localStorage.getItem("reason")
      if(!reason){
        const reason_ = pluginInfo.options[0].value
        localStorage.setItem("reason", reason_);
      }
      resolve(true);
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * @description: 获取快手配置信息
 * @return {*}
 */
async function getKSConfiguration() {
  await ksApiGetQuotaApplyList();
  const { source } = globalData;
  pluginInfo.options = tabTypes.find((item) => item.source === source).options;
}

/**
 * @description: 获取抖店配置信息
 * @return {*}
 */
async function getDDConfiguration() {

  const applicationNum = await getReceiveInfoViewQuotaInfo()

  if(applicationNum){
    pluginInfo.applicationNum = applicationNum
  }
  const options = await getApplyQuotaReason()
  if(options){
    pluginInfo.options.splice(0)
    pluginInfo.options.push(...options)
  }
}

/**
 * @description: 鉴权
 * @param {*} source
 * @param {*} shopId
 * @return {*}
 */
function authentication(source, shopId) {
  return new Promise((resolve) => {
    getAccountAuth(source, shopId).then(async (res) => {
      // state 店铺状态 1-正常 2-异常停止 3-暂停 4-未开通 5-参数错误 6-店铺不存在
      // 调试 快手店铺时 暂时设置为6  抖店时设置为1    上线设置为1
      if (res && res.state === 1) {
        resolve(await setPopupStatus())
      } else {
          resolve(false);
      }
    });
  });
}

/**
 * @description: 设置popup的状态
 * @return {*}
 */
function setPopupStatus(){
  return new Promise((resolve, reject) => {
    try {
      if(globalData.loopId){
        chrome.runtime.sendMessage(
          {
            type: "looping",
          },
          function (response) {
            resolve(true);
          }
        );
      }else{
        chrome.runtime.sendMessage(
          {
            type: "authority",
          },
          function (response) {
            resolve(true);
          }
        );
      }
    } catch (error) {
      reject(error)
    }
  })
}

/**
 * @description: 注入js
 * @param {*} jsPath
 * @param {*} callback
 * @return {*}
 */
function injectJs(jsPath, callback) {
  jsPath = jsPath || "js/inject.js";
  var temp = document.createElement("script");
  temp.setAttribute("type", "text/javascript");
  temp.src = chrome.runtime.getURL(jsPath);
  temp.onload = function () {
    callback && callback();
    this.parentNode.removeChild(this);
  };
  document.body.appendChild(temp);
}

/**
 * @description: 检查插件配置是否
 * @param {*} pluginInfo
 * @return {*}
 */
// function pluginReadyCheck(pluginInfo){
//   if (pluginInfo.pluginReplay){
//     stopMainLoop();
//     plugin_log("Plugin Ready",pluginInfo);
//     startMainLoop(pluginInfo)
//   }
// }

/**
 * @description: 获取插件信息
 * @return {*}
 */
function getPluginInfo() {
  const { source } = globalData;
  let { options } = pluginInfo;
  const reason = localStorage.getItem("reason") || 0;
  const desc = localStorage.getItem("desc") || "";
  const interval = Number(localStorage.getItem("interval")) || 120;
  const delay = Number(localStorage.getItem("delay")) || 30;
  const inputData = { reason, desc, interval, delay };

  // switch(source){
  //   case 10:
  //     break;
  //   case 7:

  //   break;
  // }

  return { source, options, inputData };
}

/**
 * @description: 关闭轮巡
 * @return {*}
 */
function stopMainLoop() {
  clearInterval(globalData.loopId);
  globalData.loopLock = false
  clearInterval(globalData.loopLockCheckId);
  setPopupStatus()
}

/**
 * @description: 开启核心轮巡
 * @return {*}
 */
function startMainLoop() {
  clearInterval(globalData.loopId);
  clearInterval(globalData.loopLockCheckId);
  globalData.startDate = new Date().getTime();
  showLoading();

  checkFeasible()
      .then(async (res) => {
        if (res) {
          const flag = await applyPromotionQuota();
        }
      })
      .catch((err) => {
        console.log("err  ", err);
        
      });

  globalData.loopId = setInterval(() => {
    
    checkFeasible()
      .then(async (res) => {
        if (res) {
          const flag = await applyPromotionQuota();
        }
      })
      .catch((err) => {
        console.log("err  ", err);
      });
  }, pluginInfo.interval * 1000);
  setPopupStatus()
}



/**
 * @description: 申请提额
 * @return {*}
 */
function applyPromotionQuota() {
  globalData.loopLock = true
  globalData.loopLockCheckId = createLockCheckTimer()
  //  店铺类型  10 快手  7 抖店
  const { source } = globalData;
  return new Promise(async (resolve, reject) => {
    try {
      let flag = false;
      switch (source) {
        case 7:
          flag = await applyPromotionQuotaDD();
          break;
        case 10:
          flag = await applyPromotionQuotaKS();
          break;
      }
      resolve(flag);
      globalData.loopLock = false
      clearInterval(globalData.loopLockCheckId);
      globalData.loopLockCheckTimes = 0;
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * @description: 获提额脚本超时检测器
 * @return {*}
 */
function createLockCheckTimer(){
  return setInterval(function(){
     globalData.loopLockCheckTimes++
     if ((pluginInfo.delay - 3) < globalData.loopLockCheckTimes){
      showMessage("message", "提额申请时间超时，将创新提额");
      clearInterval(globalData.loopLockCheckId)
      launchFn()
      // setTimeout(() => {
      //   window.history.go(0)
      // }, 3 * 1000)
     }
     // 解除监测
     if (!globalData.loopLock){
       globalData.loopLockCheckTimes = 0;
       clearInterval(globalData.loopLockCheckId)
     }
   },1000)
 }


/**
 * @description: 检查是否可以提额
 * @return {*}
 */
function checkFeasible() {
  return new Promise((resolve, reject) => {
    // if (checkDate()) {
    //   window.history.go(0);
    //   return resolve(false);
    // }
    if (globalData.loopLock) {
      return resolve(false);
    }
    checkAuditResult()
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * @description: 检查开启循环的时间是否超过24小时
 * @return {*}
 */
function checkDate() {
  const dateGap = 1000 * 60 * 60 * 24 * 1;
  const currentDate = new Date().getTime();
  return currentDate - globalData.startDate > dateGap;
}

/**
 * @description: 查看审核结果
 * @return {*}
 */
function checkAuditResult() {
  
  //  店铺类型  10 快手  7 抖店
  const { source } = globalData;
  return new Promise(async (resolve, reject) => {
    try {
      let flag = false;
      // 审核查询结果 1 审核中，不可继续申请  2 审核不通过，可继续申请  3 审核通过，未到可申请最高额度，可继续申请  4 审核通过，已是最高额度，不可继续申请    5 不可申请
      let status = 0;
      switch (source) {
        case 7:
          status = await checkAuditResultDD();
          break;
        case 10:
          status = await checkAuditResultKS();
          break;
      }
      // 调试
      // status = 3
      switch (status) {
        case 1:
          showMessage("message", "申请正在审核中，审核结束后将再次发起提额，请耐心等待～");
          break;
        case 2:
          showMessage("message", "oh，no，审核没有通过，准备再次发起审核");
          flag = true
          break;
        case 3:
          flag = true
          break;
        case 4:
          // showMessage("message", "当前已是最高额度～");
          // $('#loadTitle span').text('当前已是最高额度')
          // $('#stopLoop').text('关闭')
          // stopMainLoop()
          // chrome.runtime.sendMessage(
          //   {
          //     type: "stopLoop",
          //   },
          //   function (response) {
          //     console.log("response - ", response);
          //     resolve(true);
          //   }
          // );
          break;
          case 5:
            // showMessage("message", "当前不可申请～");
            // stopMainLoop()
          break;
      }
      resolve(flag);
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * @description: 获取表单数据
 * @param {*} data
 * @return {*}
 */
function getFormData(data) {
  const { reason, desc, interval, delay } = data;
  localStorage.setItem("reason", reason);
  localStorage.setItem("desc", desc);
  localStorage.setItem("interval", interval);
  localStorage.setItem("delay", delay);
  pluginInfo["reason"] = reason;
  pluginInfo["desc"] = desc;
  pluginInfo["interval"] = Number(interval);
  pluginInfo["delay"] = Number(delay);
}

/**
 * @description: 启动
 * @return {*}
 */
function launchFn() {
  stopMainLoop();
  startMainLoop();
}

/**
 * @description: 停止
 * @return {*}
 */
 function stopFn() {
  $('#stopLoop').click()
}

/**
 * @description: 接收inject的信息，结束脚本运行
 * @return {*}
 */
window.addEventListener(
  "message",
  function (e) {
    if (e.data.bbtPluginHandle === "stop") {
      // stopMainLoop();
      let loadDiv = $("#loadDiv");
      let closeUrl = chrome.runtime.getURL("../asset/img/close.png");
      const loadDivHtml = `
        <div
          style="margin: auto; width: 600px;background: #FFFFFF;border-radius: 4px;padding: 18px 24px;box-sizing: border-box;position: relative;">
          <img src=${closeUrl} style="width:24px;height:24px;position:absolute;top:18px;right:24px;cursor: pointer;" onclick="closeConfirmScript()" />
          <div style="font-size: 18px;font-weight: 500;color: #000000;font-size: 18px;margin-bottom: 32px;">
            提示
          </div>
          <div style="font-size: 14px;color: #666666;margin-bottom: 42px;">
            确认要停止客易达提额助手吗？停止后如需要继续提额解密请重新启动提额助手网页插件
          </div>
          <div style="display: flex;justify-content: flex-end;;width: 100%;">
            <div
              style="cursor: pointer;width: 88px;height: 36px;background: #fff;border-radius: 3px;border: 1px solid #ccc;text-align: center;line-height: 36px;font-size: 14px;color: #666;margin-right: 10px;"
              onclick="closeConfirmScript()">
              取消
            </div>
            <div
              style="cursor: pointer;width: 88px;height: 36px;background: #1677FF;border-radius: 3px;text-align: center;line-height: 36px;font-size: 14px;color: #FFFFFF;"
              onclick="stopLoopFnScript()">
              确定
            </div>
          </div>
        </div>
      `;
      loadDiv.html(loadDivHtml);
    }else if(e.data.bbtPluginHandle === "close"){
      stopMainLoop();
      $('#loadDiv').remove()
    }else if(e.data.bbtPluginHandle === "stopLoopFn"){
      stopLoopFn()
    }else if(e.data.bbtPluginHandle === "closeConfirm"){
      closeConfirm()
    }
  },
  false
);

/**
 * @description: 停止沦陷
 * @return {*}
 */
function stopLoopFn(){
  stopMainLoop()
  window.history.go(0)
}

/**
 * @description: 关闭确认框
 * @return {*}
 */
function closeConfirm(){
  $('#loadDiv').remove()
  showLoading()
}

/**
 * @description: 监听
 * @return {*}
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {

  const { type, data } = message;
  switch (type) {
    case "getPluginInfo":
      sendResponse(getPluginInfo());
      break;
    case "launch":
      getFormData(data);
      launchFn();
      break;
    case "stop":
      stopFn()
      break;
    case 'init':
      init()
    break;
  }
});

/**
 * @description: dom加载完成
 */
document.addEventListener("DOMContentLoaded", function () {
  init(() => {
    console.log("init init - --    ", new Date().getTime());
  });
});
